import pymysql


def get_cursor():
    """
    获取数据游标对象
    :return:
    """
    conn = pymysql.connect(host='192.168.88.161', port=3306, user='root', passwd='123456', db='db_users')
    cur = conn.cursor()
    return cur, conn


def close(cur, conn):
    cur.close()
    conn.close()


def register(username, password):
    """
    注册用户信息
    :param username:用户名
    :param password: 密码
    :return:
    """
    # 获取数据库操作游标
    cur, conn = get_cursor()

    # 添加用户信息
    sql = 'insert into user (username, password) values (%s, %s)'
    res = cur.execute(sql, (username, password))
    if res == 1:
        print("注册成功")
    else:
        print("注册失败")

    # 提交事务
    conn.commit()

    # 释放资源
    close(cur, conn)


def login(username, password):
    """
    判断用户登陆信息
    :param username:
    :param password:
    :return:
    """
    # 获取数据库连接和游标
    cur, conn = get_cursor()

    # 查询用户信息
    sql = "select * from user"
    res = cur.execute(sql)
    result = cur.fetchall()

    # 判断用户信息是否正确
    for id, username_i, password_i in result:
        # print(username_i, password_i)
        if username_i == username and password_i == password:
            print(f"恭喜您, {username_i}，登录成功！！！")
            break
    else:
        print("登录失败")


if __name__ == '__main__':
    # register(username='zhangsan', password='123456')

    login(username='zhangsan', password='1234567')


# 需求：如果登录信息不正确可以判断登陆失败，但是失败原因是什么？

# 需求：密码应该保存为密文？通过对象加密之后的密码是否登陆成功，MD5 SHA1 ----hashlib库
